#include "filewriterimpl.h"

#include <QFile>
#include <QTextStream>

/*
	Constructor : setup the file name and the model.
*/
FileWriter::FileWriter(const QString &file, Model *model)
{
    m_fileName = file;
    m_model = model;
}

/*
	Write the model using the tree structure.
*/
void FileWriter::Write(QTreeWidget *treeWidget)
{
	QTextStream out;
	QFile file;
	
	// Create the base element "document".
    QDomElement root = m_doc.createElement("document");
    m_doc.appendChild(root);
	
	// Setup the file
    file.setFileName(m_fileName);
    if (!file.open(QIODevice::WriteOnly))
        return;        
    out.setDevice(&file);

	// Process the nodes.
    for (int i = 0; i < treeWidget->topLevelItemCount(); i++)
        processItem(&root, treeWidget->topLevelItem(i));

    // Insert <?xml version="1.0" ?> at the begining of the document.
    QDomNode node = m_doc.createProcessingInstruction("xml","version=\"1.0\"");
    m_doc.insertBefore(node, m_doc.firstChild());
    // write the file.
    m_doc.save(out, 2);
    file.close();
}

/*
	Process nodes.
*/
void FileWriter::processItem(QDomElement *parent, QTreeWidgetItem *item)
{
    QString type;
    QString name;
    QString data;
    // Get index of data in the model, from the tree item.
    int index = item->data(0, Qt::UserRole).toUInt();
    // Get information from the model.
    type = m_model->getType(index);
    name = m_model->getName(index);
    data = m_model->getData(index);

    if (type == "CATEGORY")
    {
    	// Add an element node with its attibutes.
    	QDomElement element = m_doc.createElement("element");
		parent->appendChild(element);     
		element.setAttribute("type", "CATEGORY");
		if (item->isExpanded())
			element.setAttribute("expanded", "true");
		else
			element.setAttribute("expanded", "false");
		
		// Add the name node.
		QDomElement nameNode = m_doc.createElement("name");
		element.appendChild(nameNode);
		QDomText nameText = m_doc.createTextNode(name);
		nameNode.appendChild(nameText);     

		// A category can have sub-nodes : process them.
    	for (int i = 0; i < item->childCount(); i++)
	        processItem(&element, item->child(i));
    }
    else if (type == "PAGE")
    {
    	// Add an element node with its attibutes.
    	QDomElement element = m_doc.createElement("element");
		parent->appendChild(element);     
		element.setAttribute("type", "PAGE");
		
		// Add the name node.
		QDomElement nameNode = m_doc.createElement("name");
		element.appendChild(nameNode);
		QDomText nameText = m_doc.createTextNode(name);
		nameNode.appendChild(nameText);
		
		// Add the data node.
		QDomElement dataNode = m_doc.createElement("data");
		element.appendChild(dataNode);
		QDomCDATASection dataText = m_doc.createCDATASection(data);
		dataNode.appendChild(dataText);
    }
}
